//
//  ZCPreparationTaskViewController.m
//  ZhiChe-Wms
//
//  Created by grj on 2018/12/17.
//  Copyright © 2018 Regina. All rights reserved.
//

#import "ZCPreparationTaskViewController.h"
#import "ZCPutInStorageTableViewCell.h"
#import "ZCPreparationModel.h"
#import "ZCPreparationDetailViewController.h"
#import "UWRQViewController.h"


static NSString *prepareCellID = @"ZCPutInStorageTableViewCell";

@interface ZCPreparationTaskViewController ()<UITableViewDelegate, UITableViewDataSource, uwRQDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *listArray;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIButton *pickButton;
@property (nonatomic, strong) UIButton *checkButton;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, assign) BOOL checkVin;
@property (nonatomic, assign) BOOL takeTask;
@end

@implementation ZCPreparationTaskViewController
#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT - space(90)) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        [_tableView registerClass:[ZCPutInStorageTableViewCell class] forCellReuseIdentifier:prepareCellID];
    }
    return _tableView;
}

- (NSMutableArray *)listArray {
    if (!_listArray) {
        _listArray = [NSMutableArray array];
    }
    return _listArray;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREENHEIGHT - space(90), SCREENWIDTH, space(90))];
        _bottomView.backgroundColor = [UIColor whiteColor];
    }
    return _bottomView;
}

- (UIButton *)pickButton {
    if (!_pickButton) {
        _pickButton = [[UIButton alloc] init];
        [_pickButton setTitle:@"一键领取" forState:UIControlStateNormal];
        [_pickButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_pickButton setBackgroundColor:ZCColor(0xff8213, 1)];
        [_pickButton addTarget:self action:@selector(pickUpTask:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _pickButton;
}

- (UIButton *)checkButton {
    if (!_checkButton) {
        _checkButton = [[UIButton alloc] init];
        [_checkButton setTitle:@"一键校验" forState:UIControlStateNormal];
        [_checkButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_checkButton setBackgroundColor:ZCColor(0xff8213, 1)];
        [_checkButton addTarget:self action:@selector(checkCar:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _checkButton;
}

- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] init];
        _lineView.backgroundColor = [UIColor whiteColor];
    }
    return _lineView;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"备料明细";
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backToForward:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.pickButton];
    [self.bottomView addSubview:self.checkButton];
    [self.bottomView addSubview:self.lineView];
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
    [self updateViewConstraints];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = @"";
    [self loadData];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.checkVin = NO;
    self.takeTask = NO;
}

#pragma mark - 按钮点击
- (void)backToForward:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

//实车校验
- (void)checkCar:(UIButton *)sender {
    NSMutableArray *vinArray = [NSMutableArray array];
    NSMutableArray *qrArray = [NSMutableArray array];
    for (ZCPreparationModel *model in self.listArray) {
        if ([model.status isEqualToString:@"20"] && [model.vehicleCheckoutStatus isEqualToString:@"0"]) {
            [vinArray addObject:model.lotNo1];
            if (model.qrCode.length > 0) {
                [qrArray addObject:model.qrCode];
            }else {
                [qrArray addObject:@"dd"];
            }
            
        }
    }
    UWRQViewController *uwVC = [[UWRQViewController alloc] init];
    uwVC.delegate = self;
    uwVC.sweepStill = YES;
    uwVC.vinArr = [vinArray copy];
    uwVC.qrArr = [qrArray copy];
    [self.navigationController pushViewController:uwVC animated:YES];
}

//一键领取
- (void)pickUpTask:(UIButton *)sender {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.taskInfoId forKey:@"condition[headerId]"];
    __weak typeof(self)weakSelf = self;
    self.hud.mode = MBProgressHUDModeIndeterminate;
    self.hud.label.text = nil;
    [self.hud showAnimated:YES];
    [ZCHttpTool postWithURL:GetPrepareTask params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == 0) {
            weakSelf.takeTask = YES;
            [weakSelf.hud hideAnimated:YES];
            [weakSelf loadData];
        }else {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = responseObject[@"message"];
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        weakSelf.hud.mode = MBProgressHUDModeText;
        weakSelf.hud.label.text = error.localizedDescription;
        [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
    }];
    
}

#pragma mark - uwDelegate
- (void)uwRQFinishedStillScan:(NSArray *)resultArray {
    NSLog(@"-------ppo:%@",resultArray);
    NSMutableString *taskCode = [NSMutableString string];
    NSMutableString *taskIds = [NSMutableString string];
    for (int i = 0; i < resultArray.count; i++) {
        [taskCode appendString:resultArray[i]];
        if (i < resultArray.count - 1) {
            [taskCode appendString:@";"];
        }
        for (ZCPreparationModel *model in self.listArray) {
            if ([model.lotNo1 isEqualToString:resultArray[i]] || [model.qrCode isEqualToString:resultArray[i]]) {
                [taskIds appendString:model.Id];
                if (i < resultArray.count - 1) {
                    [taskIds appendString:@";"];
                }
            }
        }
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:taskCode forKey:@"condition[keyVins]"];
    [params setObject:taskIds forKey:@"condition[lineIds]"];
    __weak typeof(self)weakSelf = self;
//    self.hud.mode = MBProgressHUDModeIndeterminate;
    [self.hud showAnimated:YES];
    [ZCHttpTool postWithURL:VehicleCheck params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == 0) {
            weakSelf.checkVin = YES;
            [weakSelf.hud hideAnimated:YES];
            [weakSelf loadData];
//            [weakSelf.hud hideAnimated:YES];
        }else {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = responseObject[@"message"];
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        weakSelf.hud.mode = MBProgressHUDModeText;
        weakSelf.hud.label.text = error.localizedDescription;
        [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
    }];
    
}

#pragma mark - 网络请求
- (void)loadData {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.taskInfoId forKey:@"condition[preHeaderId]"];
    
    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    [ZCHttpTool postWithURL:PrepareListDetail params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] integerValue] == 0) {
            if (weakSelf.takeTask) {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = @"领取成功";
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                
            }else if (weakSelf.checkVin) {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = @"校验成功";
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }else {
                [weakSelf.hud hideAnimated:YES];
            }
            
            [weakSelf.listArray removeAllObjects];
            NSArray *dataArray = responseObject[@"data"];
            for (NSDictionary *dic in dataArray) {
                ZCPreparationModel *preparationM = [ZCPreparationModel yy_modelWithJSON:dic];
                [weakSelf.listArray addObject:preparationM];
            }
            [weakSelf.tableView reloadData];
        }else {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = responseObject[@"message"];
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        weakSelf.hud.mode = MBProgressHUDModeText;
        weakSelf.hud.label.text = error.localizedDescription;
        [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.listArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCPutInStorageTableViewCell *prepareCell = [tableView dequeueReusableCellWithIdentifier:prepareCellID forIndexPath:indexPath];
    prepareCell.selectionStyle = UITableViewCellSelectionStyleNone;
    prepareCell.typeTitle = @"发货仓库";
    prepareCell.statusTitle = @"状态";
    ZCPreparationModel *preparationM = self.listArray[indexPath.section];
    prepareCell.preparationModel = preparationM;
    return prepareCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(360);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(20);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCPreparationDetailViewController *detailVC = [[ZCPreparationDetailViewController alloc] init];
    ZCPreparationModel *preparationM = self.listArray[indexPath.section];
    detailVC.houseId = preparationM.storeHouseId;
    detailVC.key = preparationM.Id;
    detailVC.visitType = @"CLICK";
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - 布局
- (void)updateViewConstraints {
    [super updateViewConstraints];
    __weak typeof(self)weakSelf = self;
    [self.pickButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.bottomView.mas_left);
        make.bottom.equalTo(weakSelf.bottomView.mas_bottom);
        make.top.equalTo(weakSelf.bottomView.mas_top);
        make.right.equalTo(weakSelf.lineView.mas_left);
    }];
    
    [self.checkButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.lineView.mas_right);
        make.top.equalTo(weakSelf.bottomView.mas_top);
        make.bottom.equalTo(weakSelf.bottomView.mas_bottom);
        make.right.equalTo(weakSelf.bottomView.mas_right);
    }];
    
    [self.lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.bottomView.mas_top);
        make.bottom.equalTo(weakSelf.bottomView.mas_bottom);
        make.centerX.equalTo(weakSelf.bottomView.mas_centerX);
        make.width.mas_equalTo(1);
    }];
}

@end
